package com.whpost.api.controller.stamp;


import cn.dev33.satoken.stp.StpUtil;
import com.whpost.api.utils.ApiUtils;
import com.whpost.service.dao.stamp.*;
import com.whpost.service.dao.t.TCzyDao;
import com.whpost.service.entity.stamp.StampCard;
import com.whpost.service.entity.stamp.StampHd;
import com.whpost.service.entity.stamp.StampHdMb;
import com.whpost.service.entity.stamp.StampXm;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Controller
@RequestMapping("/stamp/tp")
public class StampXstpController {

    @Resource
    private StampXmMapper stampXmMapper;
    @Resource
    private StampHdMapper stampHdMapper;
    @Resource
    private StampHdMbMapper stampHdMbMapper;
    @Resource
    private StampCardMapper stampCardMapper;
    @Resource
    private TCzyDao tCzyDao;
    @Resource
    private StampH5SpMapper stampH5SpMapper;

    /**
     * 项目背景图片展示
     * @return
     */
    @RequestMapping(value = "/xmbj",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] xmbj(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampXm stampXm = new StampXm();
            stampXm = stampXmMapper.selectById(id);
            String wj = stampXm.getBjtp();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\xm\\"+stampXm.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/xm/"+stampXm.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 项目二维码
     * @param id
     * @return
     */
    @RequestMapping(value = "/qrcode",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] qrcode(String id) {
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampXm stampXm = new StampXm();
            stampXm = stampXmMapper.selectById(id);
            String wj = stampXm.getQrcode();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\xm\\"+stampXm.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/xm/"+stampXm.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 活动首页展示图片
     * @return
     */
    @RequestMapping(value = "/hdzs",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] hdzs(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getBjtp();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 定位图
     * @return
     */
    @RequestMapping(value = "/dwt",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] dwt(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getDwt();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 横版相框
     * @return
     */
    @RequestMapping(value = "/hbxk",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] hbxk(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getHbxk();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 竖版相框
     * @return
     */
    @RequestMapping(value = "/sbxk",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] sbxk(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getSbxk();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 个性化模版
     * @return
     */
    @RequestMapping(value = "/gxhmb",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] gxhmb(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getGxhMb();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 活动首页展示图片
     * @return
     */
    @RequestMapping(value = "/gxhmb_slt",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] gxhmbSlt(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getGxhMbSlt();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 活动首页展示图片
     * @return
     */
    @RequestMapping(value = "/gxhxk",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] gxhxk(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                    ToolBean.info("id:"+id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getGxhxk();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }
            ToolBean.info("gxhxk准备展示的路径："+lj);
            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 活动制作页背景图片
     * @return
     */
    @RequestMapping(value = "/hdbj",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] hdbj(String id){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    return null;
                }
            }
            StampHd stampHd;
            stampHd = stampHdMapper.selectById(id);
            String wj = stampHd.getBjtp1();
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\hd\\"+stampHd.getId()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/hd/"+stampHd.getId()+"/" + wj;
            }

            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 展示模版图片，sfslt=1表示显示缩略图
     * @param id
     * @param sfslt
     * @return
     */
    @RequestMapping(value = "/mbtp",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] mbtp(String id,String sfslt){
        try {
            if (!StringUtils.isEmpty(id)) {
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
            StampHdMb stampHdMb;
            stampHdMb = stampHdMbMapper.selectById(id);
            String wj="";
            if ("1".equals(sfslt)){
                wj = stampHdMb.getMblj1();
            }else{
                wj = stampHdMb.getMblj();
            }
            String lj = "";
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                lj = "d:\\stamp\\mb\\"+stampHdMb.getLx()+"\\" + wj;
            } else {
                //linux
                lj = "/home/stamp/mb/"+stampHdMb.getLx()+"/" + wj;
            }
            ToolBean.info("展示的图片："+lj);
            File file = new File(lj);
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 我的照片显示，这里需要鉴权，只能自己查看自己的照片
     * @param id
     * @return
     */
    @RequestMapping(value = "/wdzp",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzp(String id,String token) {
        try {
            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }
            id = Url.decrypt(id);
            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.selectById(id);
            if (null!=stampCard){
                if (!stampCard.getTHyxxId().equals(Long.parseLong(loginId))) {
                    return null;
                }
                ToolBean.info("wdzp:"+stampCard.getWjlj());
                File file = new File(stampCard.getWjlj());
                FileInputStream inputStream = null;

                inputStream = new FileInputStream(file);

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes, 0, inputStream.available());
                return bytes;
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 我的照片显示，这里需要鉴权，只能自己查看自己的照片
     * @param id
     * @return
     */
    @RequestMapping(value = "/wdzp_id",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzpid(String id,String token) {
        try {
            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }
            //id = Url.decrypt(id);
            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.selectById(id);
            if (null!=stampCard){
                if (!stampCard.getTHyxxId().equals(Long.parseLong(loginId))) {
                    return null;
                }
                ToolBean.info("wdzp:"+stampCard.getWjlj());
                File file = new File(stampCard.getWjlj());
                FileInputStream inputStream = null;

                inputStream = new FileInputStream(file);

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes, 0, inputStream.available());
                return bytes;
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //活动模板 模板id
    @RequestMapping(value = "/wdzp_gxh",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzp_gxh(String id,String token) {
        try {

            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }
            id = Url.decrypt(id);

            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.selectById(id);
            if (!stampCard.getTHyxxId().equals(Long.parseLong(loginId))) {
                return null;
            }
            File file = new File(stampCard.getWjljZs());
            ToolBean.info("wdzp_gxh:"+stampCard.getWjljZs());
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    //活动模板 模板id
    @RequestMapping(value = "/wdzp_gxh_id",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzp_gxh_id(String id,String token) {
        try {

            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }

            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.selectById(id);
            if (!stampCard.getTHyxxId().equals(Long.parseLong(loginId))) {
                return null;
            }
            File file = new File(stampCard.getWjljZs());
            ToolBean.info("wdzp_gxh:"+stampCard.getWjljZs());
            FileInputStream inputStream = null;

            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 我的照片展示图，小图
     * @param id
     * @return
     */
    @RequestMapping(value = "/wdzp_zst",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzpZst(String id,String token) {
        try {
            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }
            //id = Url.decrypt(id);
            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.selectById(id);
            if (null!=stampCard){
                if (!stampCard.getTHyxxId().equals(Long.parseLong(loginId))) {
                    return null;
                }
                ToolBean.info("wdzp_zst:"+stampCard.getWjljZs());
                File file = new File(stampCard.getWjljZs());
                FileInputStream inputStream = null;

                inputStream = new FileInputStream(file);

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes, 0, inputStream.available());
                return bytes;
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 后台查询用户照片
     * @param id
     * @return
     */
    @RequestMapping(value = "/wdzp_htzs",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] wdzpHtzs(String id,String token) {
        try {
            String loginId  = (String)StpUtil.getLoginIdByToken(token);
            if (StringUtils.isEmpty(loginId)) {
                return null;
            }
            TCzy tCzy = tCzyDao.selectById(loginId);
            StampCard stampCard = new StampCard();
            stampCard = stampCardMapper.getById(Long.parseLong(id));
            ToolBean.info("loginId:"+loginId);
            ToolBean.info("stampCard:"+stampCard.getStampHd().getStampXm().getTXzjgId());
            if (null!=stampCard){
                if (!stampCard.getStampHd().getStampXm().getTXzjgId().equals(tCzy.getXzjgId())) {
                    return null;
                }
                ToolBean.info("wdzp_htzs:"+stampCard.getWjljZs());
                File file = new File(stampCard.getWjljZs());
                FileInputStream inputStream = null;

                inputStream = new FileInputStream(file);

                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes, 0, inputStream.available());
                return bytes;
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping(value = "/spfm", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] spfm(String id) {
        // 1. 验证id合法性：只允许字母、数字、下划线
        if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
            throw new IllegalArgumentException("无效的ID");
        }

        try {

            String wj = stampH5SpMapper.selectById(id).getFmmc();
            String baseDir;

            // 2. 确定基础目录
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                baseDir = "d:\\stamp\\sp\\";
            } else {
                baseDir = "/home/stamp/sp/";
            }



            // 3. 构建文件路径，并强制解析为绝对路径
            Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
            Path filePath = basePath.resolve(wj).normalize();

            ToolBean.info("filePath:"+filePath);

            // 4. 检查文件是否在基础目录内（关键！防止路径跳转）
            if (!filePath.startsWith(basePath)) {
                throw new SecurityException("访问被拒绝");
            }

            File file = filePath.toFile();
            if (!file.exists() || !file.isFile()) {
                throw new FileNotFoundException("文件不存在");
            }

            // 5. 使用NIO安全读取文件（自动处理资源）
            return Files.readAllBytes(filePath);

        } catch (FileNotFoundException e) {
            // 处理文件不存在的情况（如返回默认图片或404）
            return getDefaultImageBytes();
        } catch (Exception e) {
            // 记录异常日志，避免直接返回null
            //log.error("获取图片失败", e);
            return null;
        }
    }

    // 示例：返回默认图片
    private byte[] getDefaultImageBytes() {
        // 读取并返回默认图片的字节数组
        return new byte[0];
    }

    @RequestMapping(value = "/spvideo", produces = "video/mp4")
    public void spvideo(String id, HttpServletResponse response) {
        // 1. 严格验证id格式（只允许字母、数字、下划线）
        if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // 2. 获取文件名
        String wj;
        try {
            wj = stampH5SpMapper.selectById(id).getSpmc();
            if (wj == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // 3. 确定基础目录
        String baseDir = System.getProperty("os.name").toLowerCase().contains("windows")
                ? "d:\\stamp\\sp\\"
                : "/home/stamp/sp/";

        // 4. 构建并规范化路径
        Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
        Path filePath = basePath.resolve(wj).normalize();

        // 5. 关键校验：确保文件在允许的目录内
        if (!filePath.startsWith(basePath)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        // 6. 检查文件是否存在且为正常文件
        if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 7. 设置响应头
        response.setContentType("video/mp4");
        response.setHeader("Accept-Ranges", "bytes");

        // 8. 使用流式传输文件内容
        try (InputStream is = Files.newInputStream(filePath);
             OutputStream os = response.getOutputStream()) {

            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
        } catch (IOException e) {
            // 记录日志而不是打印堆栈跟踪
            // 客户端断开连接是正常现象，无需特殊处理
        }
    }

    @RequestMapping(value = "/yp", produces = "audio/wav")
    @ResponseBody
    public byte[] yp(String id) {
        try {
            // 1. 严格验证id格式（只允许字母、数字、下划线）
            if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
                return null; // 非法ID直接返回
            }

            // 2. 构建文件名
            String wj = stampH5SpMapper.selectById(id).getSpmc();
            String baseDir;
            String os = System.getProperty("os.name");

            // 3. 确定基础目录
            if (os != null && os.contains("Windows")) {
                baseDir = "d:\\stamp\\sp\\";
            } else {
                baseDir = "/home/stamp/sp/";
            }

            // 4. 构建并规范化路径
            Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
            Path filePath = basePath.resolve(wj).normalize();

            // 5. 关键校验：确保文件在允许的目录内
            if (!filePath.startsWith(basePath)) {
                return null; // 路径越界直接返回
            }

            File file = filePath.toFile();
            // 6. 检查文件是否存在且为正常文件
            if (!file.exists() || !file.isFile()) {
                return null;
            }

            // 7. 使用NIO安全读取文件（自动处理资源释放）
            return Files.readAllBytes(filePath);

        } catch (Exception e) {
            e.printStackTrace(); // 实际项目中建议使用日志框架
            return null;
        }
    }

    @RequestMapping(value = "/getbt")
    @ResponseBody
    public String getbt(String id) {
        try {
            // 1. 严格验证id格式（只允许字母、数字、下划线）
            if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
                return null; // 非法ID直接返回
            }

            // 2. 构建文件名
            String wj = stampH5SpMapper.selectById(id).getBtmc();

            return wj;

        } catch (Exception e) {
            e.printStackTrace(); // 实际项目中建议使用日志框架
            return null;
        }
    }

    @RequestMapping(value = "/spvideo1", produces = "video/mp4")
    public void spvideo1(String id, HttpServletResponse response) {
        // 1. 严格验证id格式（只允许字母、数字、下划线）
        if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // 2. 获取文件名
        String wj;
        try {
            wj = stampH5SpMapper.selectById(id).getSpmc1();
            if (wj == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // 3. 确定基础目录
        String baseDir = System.getProperty("os.name").toLowerCase().contains("windows")
                ? "d:\\stamp\\sp\\"
                : "/home/stamp/sp/";

        // 4. 构建并规范化路径
        Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
        Path filePath = basePath.resolve(wj).normalize();

        // 5. 关键校验：确保文件在允许的目录内
        if (!filePath.startsWith(basePath)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        // 6. 检查文件是否存在且为正常文件
        if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 7. 设置响应头
        response.setContentType("video/mp4");
        response.setHeader("Accept-Ranges", "bytes");

        // 8. 使用流式传输文件内容
        try (InputStream is = Files.newInputStream(filePath);
             OutputStream os = response.getOutputStream()) {

            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
        } catch (IOException e) {
            // 记录日志而不是打印堆栈跟踪
            // 客户端断开连接是正常现象，无需特殊处理
        }
    }

    @RequestMapping(value = "/spfm1", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] spfm1(String id) {
        // 1. 验证id合法性：只允许字母、数字、下划线
        if (id == null || !id.matches("^[a-zA-Z0-9_]+$")) {
            throw new IllegalArgumentException("无效的ID");
        }

        try {

            String wj = stampH5SpMapper.selectById(id).getFmmc1();
            String baseDir;

            // 2. 确定基础目录
            String os = System.getProperty("os.name");
            if (os != null && os.contains("Windows")) {
                baseDir = "d:\\stamp\\sp\\";
            } else {
                baseDir = "/home/stamp/sp/";
            }



            // 3. 构建文件路径，并强制解析为绝对路径
            Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
            Path filePath = basePath.resolve(wj).normalize();

            ToolBean.info("filePath:"+filePath);

            // 4. 检查文件是否在基础目录内（关键！防止路径跳转）
            if (!filePath.startsWith(basePath)) {
                throw new SecurityException("访问被拒绝");
            }

            File file = filePath.toFile();
            if (!file.exists() || !file.isFile()) {
                throw new FileNotFoundException("文件不存在");
            }

            // 5. 使用NIO安全读取文件（自动处理资源）
            return Files.readAllBytes(filePath);

        } catch (FileNotFoundException e) {
            // 处理文件不存在的情况（如返回默认图片或404）
            return getDefaultImageBytes();
        } catch (Exception e) {
            // 记录异常日志，避免直接返回null
            //log.error("获取图片失败", e);
            return null;
        }
    }
}
